import { Command } from 'commander'
//@ts-ignore
import shell from 'shelljs'
import { resolve } from 'path'
//@ts-ignore
import rimraf from 'rimraf'

// 检测当前环境是否有yalc命令
if (!shell.which('yalc')) {
  shell.echo('抱歉执行该脚本需要 yalc')
  shell.exit(1)
}

const program = new Command('yalc-clean')
program.usage(`your-package-name [-f]
e.g. 
yalc-clean @pzy/my-button     # 从yalc仓库删除 @pzy/my-button 包, 如果 @pzy/my-button 包被其他项目引用，则会删除失败
yalc-clean @pzy/my-button -f  # 从yalc仓库中强制删除 @pzy/my-button 包, 无论 @pzy/my-button 包是否被其他项目引用
`)
program.description(`用于删除yalc仓库中的包.
1. 内部会先执行: yalc dir 用于获取yalc仓库目录.
2. 再执行: yalc installations show your-package-name 查看包的引用情况，如果存在引用则询问是否强制删除. 并告知强制删除命令. 然后终止程序执行.
3. 如果 your-package-name 没有被其他项目引用或你使用的是强制删除, 则先执行: yalc installations clean your-package-name 进行清除，
4. 最后再将 your-package-name 从yalc仓库中删除
`)
program.option('-f --force', '无论包是否被其他项目引用，都强制删除')

program.version('0.0.1', '-v, --version', '输出当前版本')
program.helpOption('-h --help', '显示命令帮助信息')

program.parse(process.argv)

function executeYalcDir(sucCall: (yalcRepo: string) => void) {
  shell.exec(
    'yalc dir',
    function (code: number, stdout: string, stderr: string) {
      const yalcRepo = stdout.replace('\n', '').replace('\r\n', '')
      if (!yalcRepo) {
        shell.echo(`执行出错:未获取到yalc仓库地址`)
        shell.exit(1)
      }
      if (code === 0) {
        sucCall && sucCall(yalcRepo)
      } else {
        shell.echo(`执行出错:${stderr}`)
        shell.exit(1)
      }
    }
  )
}

function executeYalcInstallationsShow(
  forceDel: boolean,
  yalcPackageName: string,
  sucCall: () => void
) {
  shell.echo('\r\n')
  shell.exec(
    `yalc installations show ${yalcPackageName}`,
    function (code: number, stdout: string, stderr: string) {
      if (code === 0) {
        if (stdout && !forceDel) {
          shell.echo(
            `\r\n${yalcPackageName} 被其他项目引用，是否确认删除要删除? 如果确认请执行:\r\n  yalc-clean ${yalcPackageName} -f\r\n`
          )
          shell.exit(1)
        }
        sucCall && sucCall()
      } else {
        shell.echo(`执行出错:${stderr}`)
      }
    }
  )
}

function executeYalcInstallationsClean(
  yalcPackageName: string,
  sucCall: () => void
) {
  shell.exec(
    `yalc installations clean ${yalcPackageName}`,
    function (code: number, stdout: string, stderr: string) {
      if (code === 0) {
        sucCall && sucCall()
      } else {
        shell.echo(`执行出错:${stderr}`)
      }
    }
  )
}

function main() {
  const yalcPackageName = program.args[0]
  if (!yalcPackageName) return

  const forceDel = program.opts().force

  shell.echo('\r\nyalc仓库地址:')
  executeYalcDir(yalcRepo => {
    executeYalcInstallationsShow(forceDel, yalcPackageName, () => {
      executeYalcInstallationsClean(yalcPackageName, () => {
        const packageFullDir = resolve(yalcRepo, 'packages', yalcPackageName)
        rimraf(packageFullDir, (error: string) => {
          if (error) {
            shell.echo(error)
            shell.exit(1)
          } else {
            shell.echo(`\r\n已将 ${yalcPackageName} 从yalc仓库删除.`)
          }
        })
      })
    })
  })
}

main()
